<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit; // finish preflight CORS requests here
}

if ( !empty($_REQUEST[ 'debug' ]) ) {
    $random = rand(0, intval($_REQUEST[ 'debug' ]) );
    if ( $random === 0 ) {
        header("HTTP/1.0 500 Internal Server Error");
        exit;
    }
}

@set_time_limit(5 * 60);

$targetDir = '../../public/uploads/'.date('Ymd');
$uploadDir = '../../public/uploads/'.date('Ymd');
if(!is_readable($uploadDir)) {
    is_file($uploadDir) or mkdir($uploadDir,0700);
}
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds

if (isset($_REQUEST["name"])) {
    $fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
    $fileName = $_FILES["file"]["name"];
} else {
    $fileName = uniqid("file_");
}

function get_extension($file) { 
	return substr(strrchr($file, '.'), 1); 
} 

$fileName = rand(1000,9999)."_".time().".".get_extension($fileName);
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
$uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
if ($cleanupTargetDir) {
    if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
		$result['status'] = 100;
		$result['message'] = "未能打开临时目录。";
		$jsonstr = json_encode($result);
		die($jsonstr);
    }
    while (($file = readdir($dir)) !== false) {
        $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
        // If temp file is current file proceed to the next
        if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
            continue;
        }

        if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
            @unlink($tmpfilePath);
        }
    }
    closedir($dir);
}

if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
    $result['status'] = 102;
	$result['message'] = "未能打开输出流。";
	$jsonstr = json_encode($result);
	die($jsonstr);
}

if (!empty($_FILES)) {
    if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
		$result['status'] = 103;
		$result['message'] = "移动上传文件失败。";
		$jsonstr = json_encode($result);
		die($jsonstr);
    }

    if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
        $result['status'] = 101;
		$result['message'] = "未能打开输入流。";
		$jsonstr = json_encode($result);
		die($jsonstr);
    }
} else {
    if (!$in = @fopen("php://input", "rb")) {
		$result['status'] = 101;
		$result['message'] = "未能打开输入流。";
		$jsonstr = json_encode($result);
		die($jsonstr);
    }
}

while ($buff = fread($in, 4096)) {
    fwrite($out, $buff);
}

@fclose($out);
@fclose($in);
rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
$index = 0;
$done = true;
for( $index = 0; $index < $chunks; $index++ ) {
    if ( !file_exists("{$filePath}_{$index}.part") ) {
        $done = false;
        break;
    }
}

if ( $done ) {
    if (!$out = @fopen($uploadPath, "wb")) {
		$result['status'] = 102;
		$result['message'] = "未能打开输出流。";
		$jsonstr = json_encode($result);
		die($jsonstr);
    }

    if ( flock($out, LOCK_EX) ) {
        for( $index = 0; $index < $chunks; $index++ ) {
            if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                break;
            }
            while ($buff = fread($in, 4096)) {
                fwrite($out, $buff);
            }
            @fclose($in);
            @unlink("{$filePath}_{$index}.part");
        }
        flock($out, LOCK_UN);
    }
    @fclose($out);
}

//检测图片正反
/*$imgurl = str_replace("\\","/",$uploadPath);
$exif = @exif_read_data($imgurl, 0, true);
if ($exif===false) {
} else {
	if (isset($exif['IFD0']['Orientation'])) {
		$ort = $exif['IFD0']['Orientation'];
		$source = imagecreatefromjpeg($imgurl);
		switch($ort) {                  
			case 3: // 180
				$image=imagerotate($source,180,0);
				imagejpeg($image,$imgurl);
				break;         
			case 6: // 顺时针90°
				$image=imagerotate($source, -90,0);
				imagejpeg($image,$imgurl);
				break;  
			case 8: // 逆时针90°
				$image=imagerotate($source, 90,0);
				imagejpeg($image,$imgurl);
				break;
    	}
	}
}*/

//上传成功
$result['status'] = 1;
$result['path'] = str_replace("\\","/",$uploadPath);
$result['path'] = str_replace("../","/",$result['path']);
$result['path'] = str_replace("//","/",$result['path']);
$result['fileName'] = $fileName;
$jsonstr = json_encode($result);
die($jsonstr);